﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
//using System.Data;
//using System.Drawing;
using System.Linq;
//using System.Text;
using System.Windows.Forms;

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace ECS.Framework.ReportCR
{
    public partial class ReportDialog : Form
    {
        private const int PRINT_WAIT_TIME = 10000;
        public ReportDialog()
        {
            InitializeComponent();
        }

        public void ShowReport(ref ReportModule report)
        {
            report.ShowReportViewer(ref crvViewer);
        }

        private void ReportDialog_Load(object sender, EventArgs e)
        {
            try
            {
                foreach (Control control in crvViewer.Controls)
                {
                    if (control is System.Windows.Forms.ToolStrip)
                    {

                        //Default Print Button
                        //ToolStripItem tsItem = ((ToolStrip)control).Items[1];
                        //tsItem.Click += new EventHandler(tsItem_Click);
                        //tsItem.Visible = false;

                        //Custom Button
                        ToolStripItem tsNewItem = ((ToolStrip)control).Items.Add("");
                        tsNewItem.ToolTipText = "Custom Print Button";
                        tsNewItem.Image = global::E_ICS.Properties.Resources.refresh_icon;
                        tsNewItem.Tag = "99";
                        ((ToolStrip)control).Items.Insert(0, tsNewItem);
                        tsNewItem.Click += new EventHandler(Print_Click);
                    }
                }
                //foreach (ToolStrip ts in crvViewer.Controls.OfType<ToolStrip>())
                //{

                //foreach (ToolStripButton tsb in ts.Items.OfType<ToolStripButton>())
                //{
                //    //hacky but should work. you can probably figure out a better method
                //    if (tsb.ToolTipText.ToLower().Contains("print"))
                //    {
                //        //Adding a handler for our propose
                //        //tsb.Click   
                //        tsb.Click += new EventHandler(Print_Click);
                //    }
                //}
                //} 
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }

        }

        private void Print_Click(object sender, EventArgs e)
        {
            int pageCount = 0;
            object doc = null;
            string printerName = "Generic / Text Only";
            string tempString = string.Empty;
            System.Threading.AutoResetEvent printEvent = new System.Threading.AutoResetEvent(false);
            try
            {
                //check print document
                doc = crvViewer.ReportSource;
                if (doc != null && doc.GetType() == typeof(ReportDocument))
                {
                    pageCount = ((ReportDocument)doc).FormatEngine.GetLastPageNumber(new CrystalDecisions.Shared.ReportPageRequestContext());

                    if (pageCount > 0)
                    {
                        #region Default method to print
                        //((ReportDocument)doc).PrintToPrinter(1, true, 2, 2);
                        //((ReportDocument)doc).ReportClientDocument.PrintOutputController.PrintReport();
                        #endregion

                        #region Test print method 2
                        //#Test Method 2
                        //print to printer with 16 second long. Wait 20 second during print operation for
                        //the next page to print
                        //System.Drawing.Printing.PrintDocument pDoc = new System.Drawing.Printing.PrintDocument();
                        
                        if (!IsExistPrinter(printerName))
                        {
                            CommonMessageBox.ShowMessageWarning("No 'Generic / Text Only' Printer Name");
                            return;
                        }
                        tempString = GetDefaultPrinter();
                        if (!tempString.Equals(printerName))
                        {
                            tempString = printerName;
                        }
                        
                        CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions rasPROpts = new CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions();
                        //CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper rptClientDoc = new CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper();

                        //pDoc.PrinterSettings.PrinterName = "Generic / Text Only";
                        
                        rasPROpts.PrinterName = tempString;

                        // this sets the name of the print job
                        

                        for (int i = 1; i <= pageCount; i++)
                        {
                            if (i > 1)
                            {
                                
                                if (CommonMessageBox.ShowMessageConfirmYN("Print page : " + i.ToString()) == System.Windows.Forms.DialogResult.No)
                                {
                                    continue;
                                }
                            }
                            rasPROpts.JobTitle = "Weight Slip #" + i.ToString();
                            rasPROpts.RemoveAllPrinterPageRanges();
                            rasPROpts.AddPrinterPageRange(i, i);
                            ((ReportDocument)doc).ReportClientDocument.PrintOutputController.PrintReport(rasPROpts);
                            if (pageCount > 1 && i < pageCount)
                            {
                                printEvent.WaitOne(PRINT_WAIT_TIME);
                            }
                        }

                        // rasPROpts.RemoveAllPrinterPageRanges();
                        // rasPROpts.AddPrinterPageRange(1, 1);
                        // //rptClientDoc.PrintOutputController.PrintReport(rasPROpts);
                        // //((ReportDocument)doc).ReportClientDocument.PrintOutputController.PrintReport(rasPROpts);
                        // printEvent.WaitOne(20000);
                        // rasPROpts.RemoveAllPrinterPageRanges();
                        // rasPROpts.AddPrinterPageRange(2, 2);
                        //// ((ReportDocument)doc).ReportClientDocument.PrintOutputController.PrintReport(rasPROpts);
                        //#END Test Method 2
                        #endregion
                        

                        //#Test method 1
                        //PrintOptions prtOpt = ((ReportDocument)doc).ReportClientDocument.PrintOutputController.GetPrintOptions();
                        //System.Drawing.Printing.PrinterSettings printerSettings = new System.Drawing.Printing.PrinterSettings();

                        //CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions popt = new CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions();
                        //CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions popt = ((ReportDocument)doc).ReportClientDocument.PrintOutputController.GetPrintOptions();

                        //popt.PrinterName = printerSettings.PrinterName;

                        //int pageCount = ((ReportDocument)doc).Rows.Count / 6 + ((ReportDocument)doc).Rows.Count % 6;
                        //for (int i = 1; i <= pageCount; i++)
                        //{
                        //    //popt.RemoveAllPrinterPageRanges();
                        //    //popt.AddPrinterPageRange(i, i);
                        //    //((ReportDocument)doc).ReportClientDocument.PrintOutputController.PrintReport(popt);
                        //    //System.Threading.Thread.Sleep(1000);

                        //}
                        //#END Test method 1

                        //PCPrint prt = new PCPrint();
                        //System.Text.StringBuilder sb = new System.Text.StringBuilder();

                        //prt.PrinterFont = new System.Drawing.Font("FontA11", 8f);
                        //sb.Append("Test print page" + Environment.NewLine);
                        //sb.Append("12345678901234567890123456789012345" + Environment.NewLine);
                        //sb.Append("abcdefghijklmnopqrstuvwxyz" + Environment.NewLine);
                        //sb.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + Environment.NewLine + Environment.NewLine);
                        //sb.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" + Environment.NewLine);
                        //sb.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345" + Environment.NewLine + Environment.NewLine);
                        //sb.Append("test                              end");
                        //prt.TextToPrint = sb.ToString();
                        //prt.Print();
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        string GetDefaultPrinter()
        {
            string defaultPrinter = string.Empty;
            System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.PrinterSettings();
            foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                settings.PrinterName = printer;
                if (settings.IsDefaultPrinter)
                {
                    defaultPrinter = printer;
                }
            }
            return defaultPrinter;
        }

        bool IsExistPrinter(string printerName)
        {
            System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.PrinterSettings();
            foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                settings.PrinterName = printer;
                if (printerName.Equals(printer))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
